package com.xiaobaibai.schedulingTask;

import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.common.WeixinCommon;
import com.xiaobaibai.units.pay.HttpClientUnit;
import com.xiaobaibai.units.OrderWXNewsUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SchedulingTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 53 * * * ? ")
    //去获取wxAccessToken存入本地并存入redis
    private void getWxAccessToken(){
        String base="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String url = String.format(base, WeixinCommon.APPID,WeixinCommon.SECRET);
        JSONObject jsonObject = HttpClientUnit.get(url);
        if(jsonObject.getString("access_token")==null) {
            jsonObject = HttpClientUnit.get(url);
        }
        OrderWXNewsUnit.token= jsonObject.getString("access_token");
        //每次启动也要放置好,不用担心redis缓存是永久的,因为本容器摧毁时会delete掉token
        stringRedisTemplate.opsForValue().set(WeixinCommon.WxAccessToken,OrderWXNewsUnit.token);
    }


}
